<template>
  <div class="search-container">
    <!-- 在 van-search 外层增加 form 标签
    且 action 不为空 ，即可在 iOS 输入法中
    显示搜索按钮。 -->
    <form action="/" class="search-form">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
      <!-- 搜索结果 -->
      <search-result v-if="isResultShow" :search-text="searchText" />
      <!-- 联想建议 -->
      <search-suggestion
        v-else-if="searchText"
        :search-text="searchText"
        @search="onSearch"
      />
      <!-- 搜索历史记录 -->
      <search-history
        v-else
        :search-histories="searchHistories"
        @clear-search-histories="searchHistories = []"
        @search="onSearch"
      />
    </form>
  </div>
</template>

<script>
import { setItem,getItem } from "@/utils/storage";
import searchHistory from "./components/search-history.vue";
import searchSuggestion from "./components/search-suggestion.vue";
import searchResult from "./components/search-result.vue";
export default {
  name: "SearchIndex",
  data() {
    return {
      searchText: '',
      isResultShow: false, //控制结果的显示状态
      
      searchHistories: getItem("TOUTIAO_SEARCH_HISTORY") || [], // 存储历史记录
    };
  },
  methods: {
    onSearch(val) {
      this.searchText = val;
      this.isResultShow = true;
      // 存储搜索历史记录
      // 不要有重复历史记录、最新的排在最前面
      const index = this.searchHistories.indexOf(val);
      if (index !== -1) {
        this.searchHistories.splice(index, 1);
      }

      this.searchHistories.unshift(val);
      this.isResultShow = true;
    },
    onCancel() {
      this.$router.back();
    },
  },
  components: {
    searchHistory,
    searchSuggestion,
    searchResult,
  },
  watch: {
    searchHistories(val) {
      setItem("TOUTIAO_SEARCH_HISTORY", val);
    },
  },
};
</script>

<style scoped lang="less">
.search-container {
  padding-top: 108px;
  .van-search_action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
